// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const appid = "wxe9c014bf5162f47d"
const 0 = 'ece224f3310a3a0d5e0708765d0a8699'
const db = uniCloud.database()
const user = db.collection('uni-id-users')

// 生成token方法
const jwt = require('jsonwebtoken')

// 密匙
const secret = '***'


const {
	getToken,
	verifyToken
} = require('wx-common')

module.exports = {
	_before: function() { // 通用预处理器

	},
	async wxLogin(event) {
		const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
			method: 'POST',
			data: {
				appid: appid,
				secret: secret,
				js_code: event.code,
				grant_type: 'authorization_code'

			},
			dataType: 'json'
		})
		if (res.status == 200) {
			//成功返回的openid和session_key
			const wx_openid = res.data.openid
			const wx_session_key = res.data.session_key
			// 生成token
			const token = this.getToken(wx_openid)
			// 查询数据库是否有此用户
			const res_user = await user.where({
				openid: wx_openid
			})


		}
	},
	getToken(value) {
		return jwt.sign({
			value
		}, secret, {
			expiresIn: 10800
		});

	},
	verifyToken(token) {
		try {
			return jwt.verify(token, secret)
		} catch (e) {
			return false
		}
	}

}